package com.duan.common.utils.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisCommands;

import java.util.Collections;

public class RedisLimit {


    private String scripts = null;
    private static Integer limit = 200;
    private Long RESULT_CODE = 1L;

    private JedisCommands jedis;


    private RedisLimit(Builder builder) {
        this.limit = builder.limit;
        this.jedis = builder.jedis;
        scripts = ScriptUtil.buildScript("limit.lua");
    }


    /**
     *
     * @return true 表示可以正常访问 false表示访问量比较大
     */
    public boolean limit() {

        String currentTimeStr = String.valueOf(System.currentTimeMillis() /1000); //当前秒数量

        Object result = null;
        if (jedis instanceof Jedis) {
            result = ((Jedis)jedis).eval(scripts, Collections.singletonList(currentTimeStr), Collections.singletonList(limit.toString()));
        } else if (jedis instanceof JedisCluster) {
            result = ((JedisCluster)jedis).eval(scripts, Collections.singletonList(currentTimeStr), Collections.singletonList(limit.toString()));
        } else {
            throw new RuntimeException("无该对象");
        }

        if (RESULT_CODE.equals(result)){
            return true;
        }
        return false;
    }



    public static class Builder<T extends JedisCommands> {


        private T jedis;
        private Integer limit = 200;

        public Builder (T t) {
            this.jedis = t;
        }

        public Builder limit(int limit) {
            this.limit = limit;
            return this;
        }

        public RedisLimit build() {
            return new RedisLimit(this);
        }
    }

}
